package com.free.bsf.message.channel;

import com.free.bsf.core.http.DefaultHttpClient;
import com.free.bsf.core.http.HttpClient;
import lombok.Data;
import org.apache.http.entity.ContentType;

import java.net.SocketTimeoutException;


/**
 * @author: chejiangyi
 * @version: 2019-07-23 13:49
 **/
@Data
public class DingdingProvider extends AbstractMessageProvider {

    @Override
    protected String getName(){
        return "dingding";
    }

   private String url="https://oapi.dingtalk.com/robot/send?access_token={access_token}";

    @Override
    public void sendText(String text){
        if(!isEnabled())
            return;
        getTokens().forEach(t->{
            DingdingBody.Text text1 = new DingdingBody.Text();
            text1.setContent(text);
            DingdingBody dingdingBody = new DingdingBody();
            dingdingBody.setText(text1);
            dingdingBody.setMsgtype("text");
            HttpClient.Params params = HttpClient.Params.custom().setContentType(ContentType.APPLICATION_JSON).add(dingdingBody).build();
            try {
                DefaultHttpClient.Default.post(getUrl().replace("{access_token}", t), params);
            }catch (Exception e){
                if(e.getCause() instanceof SocketTimeoutException)
                {
                    //钉钉网关不一定稳定
                    return;
                }
                throw e;
            }
        });
    }


    @Data
    public static class DingdingBody
    {
        @Data
        public static class MarkDown
        {
            private String title;
            private String text;
        }
        @Data
        public static class Text
        {
            private String content;
        }
        /**
         * "markdown","text"
         */
        private String msgtype="markdown";
        private MarkDown markdown;
        private Text text;
    }
}
